package cn.nkjobsearch.html;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.sql.*;

import cn.nkjobsearch.config.Config;
import cn.nkjobsearch.config.ConfigZhilian;
import cn.nkjobsearch.mysql.MysqlConn;
import cn.nkjobsearch.publicClass.Strings;

public class ComZhilianContent extends Thread {
	public ComZhilianContent() {
		mysql = new MysqlConn();
	}

	public void run() {
		while (true) {
			getJobIdFromDB();
			if (ids.size() == 0) {
				ConfigZhilian.ZHILIAN_CONTENT_RUNNING = false;
				System.out.println("ComZhilianContent.java break");
				break;
			}
			for (int i = 0; i < ids.size(); i += 2) {
				String jobID = ids.get(i);
				String category = ids.get(i + 1);
				if (pattern(jobID, category)) {
					System.out.println(++ConfigZhilian.ZHILIAN_CONTENT_COUNT);
				}
				ConfigZhilian.ZHILIAN_CONTENT_TIMER = 0;
			}
		}
	}

	public void close() {
		mysql.close();
	}

	private MysqlConn mysql = null;
	private List<String> ids = new ArrayList<String>();

	private String makeURL(String jobID) {
		return "http://jobs.zhaopin.com/P" + jobID.substring(21) + "/CC"
				+ jobID.substring(0, 4) + "/" + jobID.substring(4, 8) + "/"
				+ jobID.substring(9, 13) + "/" + jobID.substring(13, 16)
				+ "/CC" + jobID.substring(0, 21) + ".htm";
	}

	private void getJobIdFromDB() {
		String sql = "SELECT * FROM `zhilianjobid` where `retryCnt` < '" + Config.CONTENT_MAX_TRY_NUM + "' limit 0,"
				+ Config.CONTENT_READ_ID_FROM_DB_ONCE;
		ResultSet rs = mysql.executeQuery(sql);
		if (ids.size() != 0) {
			ids.clear();
		}
		int i;
		for (i = 0; i < Config.CONTENT_READ_ID_FROM_DB_ONCE; i++) {
			try {
				if (!rs.next())
					break;
			} catch (SQLException e) {
				e.printStackTrace();
				break;
			}
			try {
				ids.add(rs.getString("jobID"));
				ids.add(rs.getString("category"));
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		try {
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private boolean pattern(String jobID, String category) {
		String htmlContent = getHTMLContent(jobID);
		Pattern patternTitle = Pattern.compile("(.)+</div>",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherTitle = patternTitle.matcher(htmlContent);
		String title = null;
		if (matcherTitle.find()) {
			title = htmlContent.substring(matcherTitle.start(), matcherTitle
					.end() - 6);
		} else {// title end
			return false;
		}

		String orgName = null;

		Pattern patternJobNature = Pattern.compile("工作性质：</span>(.)+</td>",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherJobNature = patternJobNature.matcher(htmlContent);
		String jobNature = null;
		if (matcherJobNature.find()) {
			jobNature = htmlContent.substring(matcherJobNature.start() + 12,
					matcherJobNature.end() - 5);
		}// jobNature

		Pattern patternPubDate = Pattern.compile(
				"span4freshdate\">[0-9]{4}-[0-9]{2}-[0-9]{2}</span></td>",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherPubDate = patternPubDate.matcher(htmlContent);
		String pubDate = null;
		if (matcherPubDate.find()) {
			pubDate = htmlContent.substring(matcherPubDate.start() + 16,
					matcherPubDate.end() - 12);
		}// pubDate

		Pattern patternExp = Pattern.compile("工作经验：</span>(.)+</td>",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherExp = patternExp.matcher(htmlContent);
		String exp = null;
		if (matcherExp.find()) {
			exp = htmlContent.substring(matcherExp.start() + 12, matcherExp
					.end() - 5);
		}// exp

		Pattern patternEdu = Pattern.compile("最低学历：</span>(.)+</td>",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherEdu = patternEdu.matcher(htmlContent);
		String edu = null;
		if (matcherEdu.find()) {
			edu = htmlContent.substring(matcherEdu.start() + 12, matcherEdu
					.end() - 5);
		}// edu

		Pattern patternSalary = Pattern.compile("职位月薪：</span>(.)+</td>",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherSalary = patternSalary.matcher(htmlContent);
		String salary = null;
		if (matcherSalary.find()) {
			salary = htmlContent.substring(matcherSalary.start() + 12,
					matcherSalary.end() - 5);
		}// salary

		Pattern patternCity = Pattern.compile("工作地点：</span>(.)+</td>",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherCity = patternCity.matcher(htmlContent);
		String city = null;
		if (matcherCity.find()) {
			city = htmlContent.substring(matcherCity.start() + 12, matcherCity
					.end() - 5);
		} else {// city
			return false;
		}
		Pattern patternJobIntro = Pattern.compile(
				"职位描述/要求：</div>[(\\s|\\S)]+<div class=\"bgTitle\">联系方式：",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherJobIntro = patternJobIntro.matcher(htmlContent);
		String jobIntro = null;
		if (matcherJobIntro.find()) {
			jobIntro = Strings.strip_tags(
					htmlContent.substring(matcherJobIntro.start() + 14,
							matcherJobIntro.end() - 26)).trim();
		}// jobIntro

		if (writePatternResultToDB(title, orgName, city, exp, pubDate, edu,
				category, salary, jobIntro, jobNature, "z", jobID)) {
			return true;
		}
		return false;
	}

	private String getHTMLContent(String jobID) {
		boolean startPattern = false;
		char startChar[] = { 'l', 'e', '"', '>' };
		boolean startBool[] = { false, false, false, false };
		char endChar[] = { 'c', 't', '"', '>' };
		boolean endBool[] = { false, false, false, false };
		int ch;
		InputStreamReader in = null;
		StringBuffer input = new StringBuffer();
		try {
			String url = makeURL(jobID);
			URL u = new URL(url);
			in = new InputStreamReader(u.openStream(), "UTF-8");
		} catch (Exception e) {
			if (Config.DEBUG_INFO) {
				e.printStackTrace();
			}
		}
		/**
		 * 为了减少后面的正则匹配的字符串的长度 此处仅仅匹配搜索列表界面的部分代码 即以startChar[]开头，以endChar[]结尾的部分
		 */
		try {
			while ((ch = in.read()) != -1) {
				if (!startPattern) {
					if (startBool[0]) {
						int i;
						for (i = 1; i < startBool.length && startBool[i]; i++)
							;
						if ((char) ch == startChar[i]) {
							if (i == startBool.length - 1) {
								startPattern = true;
								continue;
							}
							startBool[i] = true;
						} else {
							for (i = 0; i < startBool.length; i++) {
								startBool[i] = false;
							}
						}
					} else {
						if ((char) ch == startChar[0]) {
							startBool[0] = true;
						}
					}
					continue;
				} else {
					if (endBool[0]) {
						int i;
						for (i = 1; i < endBool.length && endBool[i]; i++)
							;
						if ((char) ch == endChar[i]) {
							if (i == endBool.length - 1) {
								break;
							}
							endBool[i] = true;
						} else {
							for (i = 0; i < endBool.length; i++) {
								endBool[i] = false;
							}
						}
					} else {
						if (endChar[0] == (char) ch) {
							endBool[0] = true;
						}
					}
					input.append((char) ch);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return input.toString();
	}

	private boolean writePatternResultToDB(String title, String orgName,
			String city, String exp, String pubDate, String edu,
			String category, String salary, String jobIntro, String jobNature,
			String fromSite, String jobURLId) {
		String sql = "INSERT INTO  `jobinfo` (`title` ,  `orgName` ,  "
				+ "`city` ,  `exp` ,  `pubDate` ,  `edu` ,  `category` ,  "
				+ "`salary` ,  `jobIntro` ,  `jobNature` ,  `fromSite` ,  `jobURLId` ) "
				+ "VALUES('"
				+ title
				+ "', "
				+ (orgName != null ? ("'" + orgName + "'") : "NULL")
				+ " , "
				+ (city != null ? ("'" + city + "'") : "NULL")
				+ ", "
				+ (exp != null ? ("'" + exp + "'") : "NULL")
				+ ", '"
				+ pubDate
				+ "', "
				+ (edu != null ? ("'" + edu + "'") : "NULL")
				+ ", "
				+ (category != null ? ("'" + category + "'") : "NULL")
				+ ", "
				+ (salary != null ? ("'" + salary + "'") : "NULL")
				+ ", "
				+ (jobIntro != null ? ("'" + jobIntro.replaceAll("'", "\\\\'") + "'")
						: "NULL")
				+ ", "
				+ (jobNature != null ? ("'" + jobNature + "'") : "NULL")
				+ ", '" + fromSite + "', '" + jobURLId + "');";
		if (mysql.executeInsert(sql)) {
			sql = "UPDATE `zhilianjobid` SET `retryCnt` = '9' WHERE `jobID` = '"
					+ jobURLId + "' LIMIT 1;";
			mysql.executeInsert(sql);
			return true;
		} else {
			sql = "UPDATE `zhilianjobid` SET `retryCnt` = `retryCnt` + 1 WHERE `jobID` = '"
				+ jobURLId + "' LIMIT 1;";
			mysql.executeInsert(sql);
			return false;
		}
	}
}
